<template>
	<view class="page">
		<view class="place">

		</view>
		<view class="zy-deta-deile">
			<uni-list :border="false">
				<uni-list-item showArrow  v-if="hasUserInfo">
					<view slot="left" class="slot-box" >
						<image class="slot-image" :src="userInfo.headicon || defaultHeadIcon" @click="toSetPage" ></image>
					</view>
					<view class="zy-column">
						<text class="slot-text" style="margin-top: 16rpx;">{{userInfo.nickname || '暂无昵称'}} </text>
						<view v-if="hasPhone">
							<text class="phone">{{userInfo.phone}}</text>
						</view>
						<!-- #ifdef MP-WEIXIN -->
						<button v-else class="zy-wx-btn zy-get-phone" open-type="getPhoneNumber" lang="zh_CN" @getphonenumber="bindGetPhoneNumber">
							获取手机号
						</button>
						<!-- #endif -->
					</view>
					<template slot="right" @click="navigateTo('/pages/address/address')">
						地址
					</template>
				</uni-list-item>
				<uni-list-item showArrow  v-else>
					<view slot="left" class="slot-box">
						<image class="slot-image" :src="defaultHeadIcon"  mode="widthFix"></image>
					</view>
					<view class="zy-column">
						<button class="zy-wx-btn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="bindGetUserInfo">
							<view class="zy-text-big zy-text-bold" style="margin-top: 16rpx;">点击登录</view>
						</button>
					</view>
					<template slot="right" >
						地址
					</template>
				</uni-list-item>
			</uni-list>
			<view class="example">
				<uni-grid :column="3" :square="false" :showBorder="false" :highlight="false"  >
					<uni-grid-item :index="0">
						<view class="grid-item-box1" @click="navigateTo('/pages/order/order')">
							<zywork-icon  type="icondingdan" color="#00aa7f" size="50"  />
							<text class="text">查看订单</text>
						</view>
					</uni-grid-item>
					<uni-grid-item :index="1">
						<view class="grid-item-box1" @click="navigateTo('/pages/coupon/coupon')">
							<zywork-icon   type="iconqianbao" color="#00aa7f" size="50"  />
							<text class="text">优惠券</text>
						</view>
					</uni-grid-item>
					<uni-grid-item :index="2">
						<view class="grid-item-box1" @click="showImg(0)">
							<zywork-icon   type="iconkefu" color="#00aa7f" size="50"  />
							<text class="text">微信客服</text>
						</view>
					</uni-grid-item>
				</uni-grid>
			</view>
		</view>
		<view class="zy-content">
			<image class="zy-img" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3127970835,513548680&fm=26&gp=0.jpg" mode=""></image>
			<view class="example" style="margin-top: 40rpx;">
				<uni-grid :column="4" :square="false" :showBorder="false" :highlight="false"  >
					<uni-grid-item  >
						<view class="grid-item-box2" @click="applyForRider">
							<image src="/static/user/wm.png" mode=""></image>
							<text v-if="isFlag.flag&&isFlag.code==3" class="text">已认证</text>
							<text v-else class="text">申请骑手</text>
						</view>
					</uni-grid-item>
					<uni-grid-item  >
						<view class="grid-item-box2" @click="navigateTo('/pages/user/feedback/feedback')">
							<image src="/static/user/fk.png" mode=""></image>
							<text class="text">功能反馈</text>
						</view>
					</uni-grid-item>
					<uni-grid-item >
						<view class="grid-item-box2" @click="navigateTo('/pages/user/help/help')">
							<image src="/static/user/bz.png" mode=""></image>
							<text class="text">问题帮助</text>
						</view>
					</uni-grid-item>
					<uni-grid-item >
						<view class="grid-item-box2" @click="showImg(1)">
							<image src="/static/user/wechat.png" mode=""></image>
							<text class="text">公众号</text>
						</view>
					</uni-grid-item>
					<uni-grid-item >
						<view class="grid-item-box1" @click="toWalletBalancePage">
							<zywork-icon type="iconshouru" size="50" color="#ff5500"></zywork-icon>
							<text class="text">我的钱包</text>
						</view>
					</uni-grid-item>
					<uni-grid-item v-if="isFlag.flag&&isFlag.code==3">
						<view class="grid-item-box1" @click="navigateTo('/pages/user/paylist/paylist')">
							<zywork-icon type="iconyinhangka" size="50" color="#00aaff"></zywork-icon>
							<text class="text">银行卡管理</text>
						</view>
					</uni-grid-item>
					<uni-grid-item >
						<view class="grid-item-box1" @click="navigateTo(1)">
							<zywork-icon type="iconchongzhi" size="50" color="#ff0000"></zywork-icon>
							<text class="text">充值</text>
						</view>
					</uni-grid-item>
					<uni-grid-item >
						<view class="grid-item-box1" @click="toSetPage">
							<zywork-icon type="iconshezhi" size="50" color="#55aa7f"></zywork-icon>
							<text class="text">设置</text>
						</view>
					</uni-grid-item>
				</uni-grid>
			</view>
		</view>
		<view v-if="showPic" class="preview-image" @tap="close" @touchmove.stop.prevent>
			<view class="mview">
				<image :src="imgUrl[imgIndex]" mode=""></image>
			</view>
		</view>
	</view>
</template>

<script>
	import uniList from '@/components/uni-list/uni-list.vue'
	import uniListItem from '@/components/uni-list-item/uni-list-item.vue'
	import zyworkIcon from '@/components/zywork-icon/zywork-icon.vue'
	import uniGrid from '@/components/uni-grid/uni-grid.vue'
	import uniGridItem from '@/components/uni-grid-item/uni-grid-item.vue'
	import {
		COUPON_PAGE,
		SHARE_PAGE,
		SET_PAGE,
		ADDRESS_PAGE,
		NOTICE_PAGE,
		ORDER_PAGE,
		COMMISSION_PAGE,
		TEAM_PAGE,
		WALLET_BALANCE_PAGE,
		WALLET_INTEGRAL_PAGE,
		COLLECTION_PAGE
	} from '@/common/page-url.js'
	import * as ResponseStatus from '@/common/response-status.js'
	import {
		BASE_URL,
		doPostForm,
		doPostJson,
		showInfoToast,
		doGet,
		nullToStr,
		DEFAULT_HEADICON,
		USER_OPENID,
		USER_TOKEN_KEY,
		MY_SHARE_CODE,
		USER_ID,
		USER_ROLES,
		USER_PHONE,
		HAS_USER_INFO,
		FRONT_BASE_URL,
		LOCAL_FILE_STORAGE,
		SHARE_CODE,
		MALL_DISTRIBUTOR_FLAG
	} from '@/common/util.js'
	export default {
		components: {
			uniList,
			uniListItem,
			zyworkIcon,
			uniGrid,
			uniGridItem
		},
		data() {
			return {
				imgIndex:0,
				showPic:false,
				imgUrl:[
					'/static/weixin.png',
					'/static/weixin.png'
				],
				urls: {
					xcxSaveUserInfoUrl: '/wx-auth/xcx-userdetail',
					xcxSavePhoneUrl: '/wx-auth/xcx-phone',
					xcxLoginUrl: '/wx-auth/xcx',
					getUserDetailUrl: '/user-userdetail/user/get',
					infoUrl: '/user-detail/user/get-info',
					getUserRolesUrl: '/user-role/user/list',
					userWalletUrl: '/user-wallet/user/one',
					distributionAmountUrl: '/account-detail/user/distribution-amount',
					couponSearchUrl: '/goods-user-coupon/user/all-cond'
				},
				defaultHeadIcon: DEFAULT_HEADICON,
				hasUserInfo: false,
				userInfo: {},
				hasPhone: false,
				frontBaseUrl: FRONT_BASE_URL,
				localFileStorage: LOCAL_FILE_STORAGE,
				user:{},
				isFlag:{}
			};
		},
		onLoad(options) {
			// #ifdef H5
			let openid = options.openid
			let token = options.token
			if (openid && token) {
				// 公众号授权登录成功返回的openid和token
				uni.setStorageSync(USER_OPENID, openid)
				uni.setStorageSync(USER_TOKEN_KEY, token)
			}
			// #endif
			this.loadData('init');
			this.loadDistribuionFlag()
		},
		onShow() {
			if(uni.getStorageSync(HAS_USER_INFO)){
				this.hasUserInfo = uni.getStorageSync(HAS_USER_INFO)
				this.getUserDetail()
			}
			this.loadDistribuionFlag()
		},
		methods: {
			/**
			 * 前往设置
			 */
			toSetPage() {
				this.navTo(SET_PAGE);
			},
			/**
			 * 加载数据
			 * @param {Object} type
			 */
			loadData(type) {
				this.judgeLogin(type);
			},
			loadDistribuionFlag() {
				doGet('/sys-config/any/distribution-config', {}, {}).then(response => {
					let [error, res] = response
					if (res.data.code === ResponseStatus.OK) {
						this.distributionFlag = res.data.data.distributionAgentSwitch
					} else {
						showInfoToast(res.data.message)
					}
				}).catch(err => {
					console.log(err)
				})
			},
			/**
			 * 检查登录
			 * @param {Object} type
			 */
			judgeLogin(type) {
				const userToken = uni.getStorageSync(USER_TOKEN_KEY);
				if (userToken) {
					uni.checkSession({
						success: () =>  {
							// 用户token存在，且微信登录状态正常，则直接获取用户信息
							this.getUserDetail()
						},
						fail: () => {
							// 重新授权登录，获取新session_key
							this.xcxLogin()
						},
					})
				} else {
					// #ifdef MP-WEIXIN
					this.xcxLogin()
					// #endif
					// #ifdef H5
					this.gzhLogin()
					// #endif
				}
				if (type === 'pullDown') {
					uni.stopPullDownRefresh();
				}
			},
			/**
			 * 小程序登入
			 */
			xcxLogin() {
				var myThis = this;
				uni.login({
					provider: 'weixin',
					success: function(wxRes) {
						let theShareCode = uni.getStorageSync(SHARE_CODE)
						if (!theShareCode) {
							theShareCode = null
						}
						const data = {
							code: wxRes.code,
							shareCode: theShareCode
						}
						doGet(myThis.urls.xcxLoginUrl, data, {}, false).then(response => {
							let [error, res] = response;
							if (res.data.code === ResponseStatus.OK) {
								// 保存用户的openid和token
								uni.setStorageSync(USER_OPENID, res.data.data[1]);
								uni.setStorageSync(USER_TOKEN_KEY, res.data.data[2]);
								if (res.data.data[0] === 'firstLogin') {
									// 第一次小程序登录，需要点击登录按钮，才能获取用户信息再保存用户信息
									uni.removeStorageSync(SHARE_CODE);
								} else {
									// 第二次开始不需要点击登录按钮，而是直接从后台获取用户信息
									myThis.getUserDetail();
								}
							} else {
								showInfoToast(res.data.message);
							}
						}).catch(err => {
							console.log(err);
						})
					}
				})
			},
			gzhLogin() {
				const shareCode = uni.getStorageSync(SHARE_CODE);
				const data = {
					extraParams : FRONT_BASE_URL + '#/pages/user/user__' + FRONT_BASE_URL + '#/pages/user/user__' + (shareCode ? shareCode : 'shareCode')
				}
				doGet('/wx-auth/to-gzh', data, {}, false).then(response => {}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户详情
			 */
			getUserDetail() {
				doGet(this.urls.getUserDetailUrl, {}, {}, true).then(response => {
					uni.hideLoading()
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						if (res.data.data.total > 0) {
							var userInfo = nullToStr(res.data.data.rows[0]);
							// var userInfo = res.data.data;
							this.userInfo = userInfo;
							if (userInfo.userDetailNickname) {
								this.userInfo.nickname = userInfo.userDetailNickname;
							}
							if (userInfo.userDetailHeadicon) {
								this.userInfo.headicon = userInfo.userDetailHeadicon;
								if (this.userInfo.headicon && this.userInfo.headicon.indexOf('http') < 0) {
									this.userInfo.headicon = FRONT_BASE_URL + this.userInfo.headicon;
								}
							}
							if (userInfo.userDetailGender) {
								this.userInfo.gender = userInfo.userDetailGender;
							}
							if (userInfo.userPhone) {
								this.hasPhone = true
								this.userInfo.phone = userInfo.userPhone;
							}
							if (this.userInfo.nickname && this.userInfo.headicon) {
								// 已经获取到了用户信息
								this.hasUserInfo = true;
								uni.setStorageSync(USER_ID, userInfo.userId);
								uni.setStorageSync(HAS_USER_INFO, true);
								// 加载其他用户数据
								this.loadOtherUserData()
							} else {
								uni.setStorageSync(HAS_USER_INFO, false);
							}
							uni.setStorageSync(USER_PHONE, userInfo.userPhone);
							uni.setStorageSync(MY_SHARE_CODE, userInfo.shareCode)
							this.loadWalletInfo();
						}
					} else if (res.data.code === ResponseStatus.AUTHENTICATION_TOKEN_ERROR) {
						// 如果token过期了，则直接使用小程序登录，获取最新的token
						uni.removeStorageSync(USER_TOKEN_KEY);
						uni.removeStorageSync(USER_OPENID);
						uni.removeStorageSync(USER_ID)
						uni.setStorageSync(HAS_USER_INFO, false);
						this.xcxLogin();
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户的角色信息
			 */
			getUserRoles() {
				doGet(this.urls.getUserRolesUrl, {}, {}, true).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						var rolesArrey = []
						uni.setStorageSync(MALL_DISTRIBUTOR_FLAG, false)
						res.data.data.rows.forEach(item => {
							rolesArrey.push(item.roleTitle);
							if (item.roleTitle.indexOf('sys_mall_distributor_v') != -1) {
								uni.setStorageSync(MALL_DISTRIBUTOR_FLAG, true)
								this.isDistribution = true
							}
							if (item.roleTitle.indexOf('sys_mall_pickup_v') != -1) {
								this.isPickUp = true
							}
						})
						uni.setStorageSync(USER_ROLES, rolesArrey);
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err);
				})
			},
			/**
			 * 获取用户信息
			 * @param {Object} e
			 */
			bindGetUserInfo(e) {
				const openId = uni.getStorageSync(USER_OPENID);
				const data = {
					openid: openId,
					nickname: e.detail.userInfo.nickName,
					headicon: e.detail.userInfo.avatarUrl,
					gender: e.detail.userInfo.gender
				};
				uni.showLoading({
					title: '登录中...'
				})
				doPostForm(this.urls.xcxSaveUserInfoUrl, data, {}, false).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						this.hasUserInfo = true;
						// this.userInfo.nickname = data.nickname;
						this.userInfo.headicon = data.headicon;
						// 设置已登录并且获取用户信息
						uni.setStorageSync(HAS_USER_INFO, true)
						// 加载其他用户数据
						this.loadOtherUserData()
					} else {
						showInfoToast(res.data.message);
					}
					uni.hideLoading()
				}).catch(err => {
					console.log(err)
				})
			},
			/**
			 * 小程序获取用户手机
			 * @param {Object} e
			 */
			bindGetPhoneNumber(e) {
				uni.showLoading({
					title: '获取中...'
				})
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					const openId = uni.getStorageSync(USER_OPENID)
					const data = {
						openid: openId,
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv
					}
					doPostForm(this.urls.xcxSavePhoneUrl, data, {}, false).then(response => {
						uni.hideLoading()
						let [error, res] = response
						if (res.data.code === ResponseStatus.OK) {
							this.userInfo.phone = res.data.data.phoneNumber
							this.hasPhone = true
							showInfoToast('已获取手机号')
						} else {
							showInfoToast(res.data.message);
						}
					}).catch(err => {
						uni.hideLoading()
						console.log(err)
					})
				} else {
					uni.hideLoading()
					showInfoToast('微信服务端未能正常返回手机号')
				}
			},
			loadOtherUserData() {
				this.getUserRoles()
				this.getApplyForRider()
			},
			/**
			 * 统一跳转接口,拦截未登录路由
			 * navigator标签现在默认没有转场动画，所以用view
			 */
			navTo(url) {
				if (!uni.getStorageSync(HAS_USER_INFO)) {
					// #ifdef MP-WEIXIN
					showInfoToast('请点击登录')
					// #endif
					// #ifdef H5
					this.gzhLogin()
					// #endif
				} else {
					uni.navigateTo({
						url
					})
				}
			},
			/**
			 * 获取钱包信息
			 */
			loadWalletInfo() {
				doGet(this.urls.userWalletUrl, {}, {}, true).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						this.userWallet = res.data.data;
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err)
				})
			},
			/**
			 * 前往用户钱包余额页面
			 */
			toWalletBalancePage() {
				this.navTo('/pages/wallet/user-wallet?userWallet=' + JSON.stringify(this.userWallet)+'&code='+this.isFlag.code)
			},
			getApplyForRider(){
				doGet("/user-certification/user/check", {}, {}, true).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						 this.isFlag = res.data.data;
					} else {
						showInfoToast(res.data.message);
					}
				}).catch(err => {
					console.log(err)
				})
			},
			applyForRider(){
				if(!this.isFlag.flag){
					this.navTo('/pages/user/user_certification/user_certification')
				}else if(this.isFlag.flag&&this.isFlag.code==1){
					showInfoToast('你已提交认证，请等待审核完毕')
				}else if(this.isFlag.flag&&this.isFlag.code==2){
					this.navTo('/pages/user/user_certification/user_certification?cid='+this.isFlag.id+"&checkDes="+this.isFlag.checkDes)
				}else if (this.isFlag.flag&&this.isFlag.code==3){
					showInfoToast('你已认证为骑手了')
				}
			},
			navigateTo(url){
				if(url==1){
					showInfoToast('待开放')
				}
				this.navTo(url);
			},
			/**
			 * 统一跳转接口,拦截未登录路由
			 * navigator标签现在默认没有转场动画，所以用view
			 */
			navTo(url) {
				if (!uni.getStorageSync(HAS_USER_INFO)) {
					// #ifdef MP-WEIXIN
					showInfoToast('请点击登录')
					// #endif
					// #ifdef H5
					this.gzhLogin()
					// #endif
				} else {
					uni.navigateTo({
						url
					})
				}
			},
			showImg(index){
				this.imgIndex = index;
				this.showPic = true;
			},
			close(){
				this.showPic = false;
			}
			
		}
	}
</script>

<style lang="scss">
	@import '@/common/zywork-main.scss';
	
	.zy-column{
		display: flex;
		flex-direction: column;
	}
	button{
		&::after{
			border: none;
		}
	}
	.zy-wx-btn {
		margin-left: 0px;
		line-height: 1;
		display: inline;
		padding: 0;
		background-color: transparent;
	}
	.zy-get-phone {
		width: 150rpx;
		height: 40rpx;
		margin-top: 5rpx;
		font-size: 30upx;
	}
	.preview-image {
		z-index: 999;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.7);
		user-select: none;
		
		.mview {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 100%;
			image {
				width: 500rpx;
				height: 500rpx;
			}
		}
		
	}
	.page{
		width: 100%;
		background-color: #eeeeee;
		height: 100%;
	}
	.place{
		background-color: #00aa7f;
		width: 100%;
		height: 270rpx;
		border-bottom-left-radius: 15%;
		border-bottom-right-radius: 15%;
	}
	.zy-deta-deile{
		padding-top: 15rpx;
		background-color: #FFFFFF;
		position: absolute;
		width: 86%;
		height:320rpx ;
		border-radius: 20rpx;
		top: 66rpx;
		left: 7%;
		z-index: 10;
	}

	.slot-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		.slot-image {
			/* #ifndef APP-NVUE */
			display: block;
			/* #endif */
			margin-right: 10px;
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}
	}
	.slot-text {
		font-size: 30rpx;
		margin-right: 16rpx;
	}
	.example{
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		@include padding;
		.grid-item-box1 {
			width: 100%;
			// height: 140rpx;
			padding: 20rpx 0rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			text{
				margin-top: 10rpx;
				color: $info-text-color;
				font-size: $font-base;
			}
		}
		.grid-item-box2 {
			width: 100%;
			// height: 140rpx;
			display: flex;
			padding: 20rpx 0rpx;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			image{
				width: 50rpx;
				height: 50rpx;
			}
			.zy-icon{
				position: absolute;
				top: -16rpx;
				z-index: 999;
			}
			text{
				margin-top: 10rpx;
				color: #6f6f6f;
				font-size: $font-sm;
			}
		}
	}
	.zy-content{
		margin-top: 140rpx;
		padding: 25rpx $padding-left-right;
		background-color: $primary-backcolor;
		.zy-img{
			width: 100%;
			height: 280rpx;
		}
	}
</style>
